package cy.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cy.dao.BaseDaoI;
import cy.model.Tmenu;
import cy.model.Tuser;
import cy.service.RepairServiceI;
import cy.util.Encrypt;

@Service("repairService")
public class RepairServiceImpl implements RepairServiceI {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(RepairServiceImpl.class);

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private BaseDaoI<Tmenu> menuDao;
	private BaseDaoI<Tuser> userDao;

	public BaseDaoI<Tmenu> getMenuDao() {
		return menuDao;
	}

	@Autowired
	public void setMenuDao(BaseDaoI<Tmenu> menuDao) {
		this.menuDao = menuDao;
	}

	public BaseDaoI<Tuser> getUserDao() {
		return userDao;
	}

	@Autowired
	public void setUserDao(BaseDaoI<Tuser> userDao) {
		this.userDao = userDao;
	}

	@Override
	synchronized public void repair() {
		repairUser();
		repairMenu();
	}

	public void repairMenu() {
		Tmenu root = new Tmenu();
		root.setId("0");
		root.setText("首页");
		root.setUrl("");
		menuDao.saveOrUpdate(root);

		Tmenu xtgl = new Tmenu();
        xtgl.setId("xtgl");
        xtgl.setTmenu(root);
        xtgl.setText("系统管理");
        xtgl.setUrl("");
        menuDao.saveOrUpdate(xtgl);
        
		Tmenu yhgl = new Tmenu();
		yhgl.setId("1yhgl");
		yhgl.setTmenu(xtgl);
		yhgl.setText("用户管理");
		yhgl.setUrl("/admin/yhgl.jsp");
		menuDao.saveOrUpdate(yhgl);

		Tmenu jsgl = new Tmenu();
		jsgl.setId("2jsgl");
		jsgl.setTmenu(xtgl);
		jsgl.setText("角色管理");
		menuDao.saveOrUpdate(jsgl);

		Tmenu qxgl = new Tmenu();
		qxgl.setId("3qxgl");
		qxgl.setTmenu(xtgl);
		qxgl.setText("权限管理");
		menuDao.saveOrUpdate(qxgl);

		Tmenu cdgl = new Tmenu();
		cdgl.setId("4cdgl");
		cdgl.setTmenu(xtgl);
		cdgl.setText("菜单管理");
		menuDao.saveOrUpdate(cdgl);

		Tmenu buggl = new Tmenu();
		buggl.setId("5buggl");
		buggl.setTmenu(xtgl);
		buggl.setText("BUG管理");
		menuDao.saveOrUpdate(buggl);
		
	}

	public void repairUser() {

		Map<String, Object> m = new HashMap<String, Object>();
		m.put("name", "admin");
		Tuser t = userDao.get("from Tuser t where t.name = :name and t.id != '0'", m);
		if (t != null) {
			userDao.delete(t);
			this.getSessionFactory().getCurrentSession().flush();
		}
		
		Tuser user = new Tuser();
		user.setId("0");
		user.setName("admin");
		user.setPwd(Encrypt.e("admin"));
		user.setModifytime(new Date());
		userDao.saveOrUpdate(user);
	}

}
